package file

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"iot-base/auth/utils"
	"net/http"
	"time"
)

type DownloadRoleInfoBo struct {
	Name        string    `json:"name"`
	Level       int       `json:"level"`
	Description string    `json:"description"`
	CreateTime  time.Time `json:"createTime"`
}

// ExcelTest API处理器函数.
func ExcelTest(c *gin.Context) {
	var roleData [2]DownloadRoleInfoBo
	roleData[0] = DownloadRoleInfoBo{
		"你好",
		1,
		"备注",
		time.Now(),
	}
	roleData[1] = DownloadRoleInfoBo{
		"你好2好",
		1,
		"备注",
		time.Now(),
	}
	// 略过向 roleData 添加数据过程
	var res []interface{}
	for _, role := range roleData {
		res = append(res, &DownloadRoleInfoBo{
			Name:        role.Name,
			Level:       role.Level,
			Description: role.Description,
			CreateTime:  role.CreateTime,
		})
	}
	content := utils.ToExcel([]string{`角色名称`, `角色级别`, `描述`, `创建日期`}, res)
	ResponseXls(c, content, "角色数据")
}
func ResponseXls(c *gin.Context, content io.ReadSeeker, fileTag string) {
	fileName := fmt.Sprintf("%s%s%s.xlsx", utils.GetNowToString(), `-`, fileTag)
	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
	c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
}
